package com.hmdp.test.lifecycle.ext;

import com.hmdp.test.lifecycle.bean.MyBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 实例化前置，后置，属性修改
 *
 * @author lizhihui
 */
@Slf4j
@Component
public class BMyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        // 默认什么都不做，返回 null
        if ("myBean".equals(beanName) && beanClass == MyBean.class) {
            log.error("1.实例化前 - BMyInstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation - beanName={}", beanName);
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        // 默认返回 true，什么也不做，继续下一步
        if ("myBean".equals(beanName) && bean.getClass() == MyBean.class) {
            log.error("3.实例化后 - BMyInstantiationAwareBeanPostProcessor.postProcessAfterInstantiation - beanName={}", beanName);
        }
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        // 此方法可对bean中的属性值进行、添加、修改、删除操作
        // 对属性值进行修改，如果postProcessAfterInstantiation方法返回false，该方法可能不会被调用
        if ("myBean".equals(beanName) && bean.getClass() == MyBean.class) {
            log.error("4.实例化后属性处理 - BMyInstantiationAwareBeanPostProcessor.postProcessProperties - beanName={}", beanName);
        }
        return null;
    }

}
